<template>
  <div class="body">
    <div class="table-wrap">
      <div class="search_header">
        <span>
          <el-button
            v-has="'roleManagement:add'"
            icon="el-icon-plus"
            @click="
              ;(dialogVisible = true),
                (headerTitle = '新增角色'),
                (add = true)
            "
            >新增角色</el-button
          >
        </span>
        <div class="search_header_right">
          <el-input
            v-model="query.roleName"
            placeholder="请输入角色名"
            clearable
            @change="searchRole"
          >
            <span
              @click="searchRole"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
        </div>
      </div>
      <el-table
        :data="roleList"
        :header-cell-style="{
          background: '#F2F6FB ',
          color: ' #6B767D'
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column
          label="创建时间"
          prop="createDate"
        />
        <el-table-column
          label="更新时间"
          prop="updateDate"
        />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="Update(scope.row)"
              style="color: #00baff; font-weight: 400"
              v-has="'roleManagement:edit'"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="deleteRole(scope.row)"
              style="color: #ff5b5b; font-weight: 400"
              v-if="
                scope.row.roleName !== '超级管理员' &&
                $filterGlobalPermission(
                  'roleManagement:delete'
                )
              "
              >删除</el-button
            >
            <el-button
              type="text"
              @click="priRole(scope.row)"
              style="color: #00baff; font-weight: 400"
              v-if="
                scope.row.roleName !== '超级管理员' &&
                $filterGlobalPermission(
                  'roleManagement:permission'
                )
              "
              >模块权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination" v-if="total">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="query.pageSize"
          @current-change="pageChange"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="headerTitle"
      @close="onClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-form
        label-width="80px"
        :model="addList"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addList.roleName" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addList.remark" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onClose">取消</el-button>
        <el-button
          type="primary"
          @click="onSumbit('ruleForm')"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 权限配置 -->
    <el-dialog
      :visible.sync="dialogPriVisible"
      :title="activeRole.roleName + '——模块权限配置'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="530px"
    >
      <div class="permission-content">
        <el-tabs v-model="priTab" stretch>
          <el-tab-pane label="平台权限" name="platform">
            <el-tree
              ref="tree"
              :default-expand-all="true"
              :data="menuTree"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              :default-checked-keys="checkedKeys"
              :check-strictly="true"
              show-checkbox
              node-key="pkid"
              highlight-current
            />
          </el-tab-pane>
          <el-tab-pane label="PAD端权限" name="pad">
            <el-tree
              ref="padTree"
              :default-expand-all="true"
              :data="padMenuTree"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              :default-checked-keys="padCheckedKeys"
              :check-strictly="true"
              show-checkbox
              node-key="pkid"
              highlight-current
            />
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <el-button @click="dialogPriVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="onSubmitRole"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 按钮编辑 -->
    <el-dialog
      :visible.sync="btnDialogVisible"
      title="按钮编辑"
      @close="handleCloseBtnDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-form
        label-width="80px"
        :model="btnForm"
        :rules="btnRules"
        ref="btnForm"
      >
        <el-form-item label="按钮名称" prop="catalogName">
          <el-input v-model="btnForm.catalogName" />
        </el-form-item>
        <el-form-item
          label="按钮编码"
          prop="pkid"
          :disabled="!isAddBtnForm"
        >
          <el-input v-model="btnForm.pkid" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseBtnDialog"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="handleSubmitBtnForm"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  roleQuery,
  roleDelete,
  roleAdd,
  roleUpdate,
  priRoleAdd,
  priRoleDelete,
  priRoleMenuQuery,
  priRoleMenuQueryNew,
  priRoleSave
} from '@/api/role'
import { treeAdd, treeUpdate } from '@/api/tree'
import Icon from '@/components/icon'

export default {
  name: 'index',
  components: {
    Icon
  },
  data() {
    return {
      priTab: 'platform',
      roleList: [],
      total: '',
      add: true,
      pkid: '',
      addList: {
        roleName: '',
        remark: ''
      },
      rules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名',
            trigger: 'blur'
          }
        ]
      },
      query: {
        pageSize: 10,
        pageIndex: 1,
        roleName: '',
        sortField: '',
        sortType: ''
      },
      headerTitle: '新增角色',
      dialogVisible: false,
      dialogPriVisible: false,
      menuTree: [],
      padMenuTree: [],
      defaultProps: {
        children: 'children',
        label: 'catalogName'
        // disabled: (_data, node) => {
        //   return this.loadingList.includes(node.key)
        // }
      },
      checkedKeys: [],
      padCheckedKeys: [],
      activeRole: {},
      activeName: 'first',

      // 按钮编辑弹窗
      isAddBtnForm: false,
      btnDialogVisible: false,
      btnForm: {},
      btnRules: {
        catalogName: [
          {
            required: true,
            message: '请输入按钮名称',
            trigger: 'blur'
          }
        ],
        pkid: [
          {
            required: true,
            message: '请输入按钮编码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 模糊查询
    searchRole() {
      this.query.pageIndex = 1
      this.getList()
    },
    pageChange(page) {
      this.query.pageIndex = page
      this.getList()
    },
    getList() {
      roleQuery(this.query).then((res) => {
        if (res.success) {
          this.roleList = res.data.list
          this.total = res.data.count
        }
      })
    },
    onSubmitRole() {
      let keys = []
      const params = []
      if (this.priTab === 'platform') {
        keys = this.$refs.tree.getCheckedKeys()
        keys.forEach((item) => {
          params.push({
            roleId: this.activeRole.pkid,
            resourceId: item,
            resourceType: '4'
          })
        })
      } else {
        keys = this.$refs.padTree.getCheckedKeys()
        keys.forEach((item) => {
          params.push({
            roleId: this.activeRole.pkid,
            resourceId: item,
            resourceType: '6'
          })
        })
      }
      priRoleSave(params).then((res) => {
        if (res.success) {
          this.$message.success('角色配置模块权限成功')
          this.dialogPriVisible = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    priRole(item) {
      this.activeRole = item
      // this.dialogPriVisible = true
      this.getPriRoleTree(item.pkid)
    },
    async getPriRoleTree(id) {
      try {
        // 平台端权限
        const menuTreeData = await priRoleMenuQueryNew({
          type: 4,
          roleId: id
        })
        if (menuTreeData.success) {
          this.menuTree = menuTreeData.data
          this.checkedKeys = []
          this.getTreeCheckId(this.menuTree)
        } else {
          this.$message.error(menuTreeData.message)
        }

        // pad端权限
        const padMenuTreeData = await priRoleMenuQuery({
          type: 6,
          roleId: id
        })
        if (padMenuTreeData.success) {
          this.padMenuTree = padMenuTreeData.data
          this.padCheckedKeys = []
          this.getPadTreeCheckId(this.padMenuTree)
        } else {
          this.$message.error(padMenuTreeData.message)
        }
        this.dialogPriVisible = true
      } catch (error) {
        this.$message.error(error)
      }
    },
    handleCheck(currentNode, data) {
      // console.log('handleCheck', currentNode, data)
      if (
        currentNode.children &&
        currentNode.children.length
      ) {
        // console.log('目录', currentNode.catalogName)
        if (
          data.checkedKeys.indexOf(currentNode.pkid) !== -1
        ) {
          // console.log('添加子模块', currentNode.children)
          priRoleAdd({
            roleId: this.activeRole.pkid,
            resourceId: currentNode.pkid,
            resourceType: '4'
          })
          currentNode.children.forEach((child) => {
            priRoleAdd({
              roleId: this.activeRole.pkid,
              resourceId: child.pkid,
              resourceType: '4'
            })
          })
        } else {
          // console.log('移除子模块', currentNode.children)
          priRoleDelete(
            this.activeRole.pkid,
            currentNode.pkid
          )
          currentNode.children.forEach((child) => {
            priRoleDelete(this.activeRole.pkid, child.pkid)
          })
        }
      } else {
        // console.log('模块', currentNode.catalogName)
        if (
          data.checkedKeys.indexOf(currentNode.pkid) !== -1
        ) {
          // console.log('添加权限')
          priRoleAdd({
            roleId: this.activeRole.pkid,
            resourceId: currentNode.pkid,
            resourceType: '4'
          })
        } else {
          // console.log('移除权限')
          priRoleDelete(
            this.activeRole.pkid,
            currentNode.pkid
          )
        }
      }
    },
    getTreeCheckId(data) {
      data.map((item) => {
        if (item.children && item.children.length) {
          if (item.hasPri) {
            this.checkedKeys.push(item.pkid)
          }
          this.getTreeCheckId(item.children)
        } else {
          if (item.hasPri) {
            this.checkedKeys.push(item.pkid)
          }
        }
      })
    },
    getPadTreeCheckId(data) {
      data.map((item) => {
        if (item.children && item.children.length) {
          if (item.hasPri) {
            this.padCheckedKeys.push(item.pkid)
          }
          this.getPadTreeCheckId(item.children)
        } else {
          if (item.hasPri) {
            this.padCheckedKeys.push(item.pkid)
          }
        }
      })
    },
    Update(item) {
      this.add = false
      this.addList.roleName = item.roleName
      this.addList.remark = item.remark
      this.headerTitle = '编辑角色'
      this.dialogVisible = true
      this.pkid = item.pkid
    },
    deleteRole(item) {
      this.$confirm(
        '此操作将永久删除该部门，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          roleDelete(item.pkid).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
              if (
                this.total % 10 === 1 &&
                this.query.pageIndex ===
                  parseInt(this.total / 10) + 1 &&
                this.query.pageIndex !== 1
              ) {
                this.query.pageIndex -= 1
              }
              this.getList()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    onSumbit(ruleForm) {
      this.$refs[ruleForm].validate((vaild) => {
        if (vaild) {
          if (this.add) {
            roleAdd(this.addList).then((res) => {
              if (res.success) {
                this.$message.success('新增角色成功')
                this.onClose()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            roleUpdate(this.addList, this.pkid).then(
              (res) => {
                if (res.success) {
                  this.$message.success(res.data)
                  this.onClose()
                } else {
                  this.$message.error(res.message)
                }
              }
            )
          }
        }
      })
    },
    onClose() {
      this.addList.remark = ''
      this.addList.roleName = ''
      this.pkid = ''
      this.dialogVisible = false
      this.getList()
    },
    // tanble row
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    filterNode(value, data) {
      if (!value) return true
      if (data.sourceName) {
        return data.sourceName.indexOf(value) !== -1
      }
    },
    // 关闭按钮编辑弹窗
    handleCloseBtnDialog() {
      this.btnForm = {}
      this.btnDialogVisible = false
    },
    // 提交按钮编辑
    handleSubmitBtnForm() {
      this.$refs.btnForm.validate((vaild) => {
        if (vaild) {
          if (this.isAddBtnForm) {
            treeAdd(this.btnForm).then((res) => {
              if (res.success) {
                this.$message.success('新增按钮成功')
                this.handleCloseBtnDialog()
                this.dialogPriVisible = false
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            treeUpdate(
              this.btnForm,
              this.btnForm.pkid
            ).then((res) => {
              if (res.success) {
                this.$message.success('更新按钮成功')
                this.handleCloseBtnDialog()
                this.dialogPriVisible = false
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';
.permission-content {
  width: 100%;
  height: 500px;
  overflow-y: hidden;

  :deep(.el-tabs) {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-tabs__content {
      flex: 1;
      overflow-y: auto;
    }
  }
}

.body::v-deep {
  .el-dialog {
    .el-dialog__header {
      background: #597182 !important;
      padding: 8px 0 14px 24px !important;
      height: 39px !important;
      .el-dialog__title {
        font-size: 16px !important;
        line-height: 22px;
        font-weight: 400 !important;
        color: white !important;
        //margin:19px 0 14px 24px !important;
      }
      .el-dialog__headerbtn {
        font-size: 16px;
        top: 10px !important;
        right: 17px !important;
        color: white !important;
        .el-dialog__close {
          color: white !important;
        }
      }
    }
    .el-dialog__body {
      padding: 17px 32px 18px 26px !important;
      .el-form-item {
        margin-bottom: 19px !important;
      }
    }
    .el-input__inner {
      //height: 34px !important;
      background-color: #f6f9fc !important;
    }
    .el-button--default {
      border-color: #497fa3 !important;
      span {
        color: #497fa3 !important;
      }
    }
    .el-button--primary {
      background: #497fa3 !important;
      border-color: white !important;
    }
  }
  .custom-tree-node {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
